<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>组织架构管理</span>
          <div>
            <el-button type="primary" @click="handleAddRoot">添加根组织</el-button>
            <el-button @click="expandAll">全部展开</el-button>
            <el-button @click="collapseAll">全部折叠</el-button>
          </div>
        </div>
      </template>

      <!-- 组织架构图 -->
      <div class="org-chart-container">
        <TreeOrg
            v-if="orgData.id"
            :data="orgData"
            :options="options"
            :props="propsConfig"
            @on-click="handleNodeClick"
            @on-contextmenu="handleContextMenu"
        />
      </div>
    </el-card>

    <!-- 右键菜单 -->
    <div
        v-show="contextMenu.visible"
        class="context-menu"
        :style="{
        left: contextMenu.x + 'px',
        top: contextMenu.y + 'px'
      }"
    >
      <div class="menu-item" @click="handleAddSameLevel">添加同级组织</div>
      <div class="menu-item" @click="handleAddSubLevel">添加下级组织</div>
      <div class="menu-item" @click="handleEdit">修改信息</div>
      <div class="menu-item danger" @click="handleDelete">删除信息</div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
        :title="dialog.title"
        v-model="dialog.visible"
        width="500px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="组织名称" prop="menuName">
          <el-input v-model="form.menuName" placeholder="请输入组织名称" />
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="visible">
          <el-radio-group v-model="form.visible">
            <el-radio label="1">显示</el-radio>
            <el-radio label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import TreeOrg from 'vue3-tree-org'
import 'vue3-tree-org/lib/vue3-tree-org.css'
import { listMenu, addMenu, updateMenu, delMenu } from '@/api/system/menu'

const orgData = ref({})
const loading = ref(false)
const formRef = ref()
const currentNode = ref(null)

// 组织架构配置
const options = ref({
  nodeKey: 'menuId',
  horizontal: false,
  collapsable: true,
  labelWidth: 180,
  renderContent: (h, { data }) => {
    return h('div', { class: 'custom-org-node' }, [
      h('div', { class: 'node-content' }, [
        h('div', { class: 'node-title' }, data.menuName),
        data.icon ? h('i', { class: `el-icon-${data.icon}` }) : null
      ])
    ])
  }
})

const propsConfig = {
  label: 'menuName',
  children: 'children',
  expand: 'expand'
}

// 右键菜单
const contextMenu = reactive({
  visible: false,
  x: 0,
  y: 0
})

// 对话框
const dialog = reactive({
  visible: false,
  title: ''
})

// 表单数据
const form = reactive({
  menuId: undefined,
  menuName: '',
  parentId: 0,
  orderNum: 0,
  visible: '1',
  menuType: 'M',
  path: '',
  perms: '',
  remark: 'org_structure' // 标识为组织架构节点
})

// 表单验证规则
const rules = {
  menuName: [
    { required: true, message: '组织名称不能为空', trigger: 'blur' }
  ]
}

// 初始化数据
onMounted(() => {
  loadOrgData()
})

// 加载组织数据
const loadOrgData = async () => {
  try {
    loading.value = true
    const res = await listMenu()
    if (res.code === 200) {
      const orgMenus = res.data.filter(menu =>
          menu.remark && menu.remark.includes('org_structure')
      )
      if (orgMenus.length === 0) {
        // 如果没有组织数据，创建默认结构
        await createDefaultStructure()
      } else {
        orgData.value = transformMenuToOrg(orgMenus)
      }
    }
  } catch (error) {
    console.error('加载组织数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 转换菜单数据为组织架构格式
const transformMenuToOrg = (menus) => {
  const menuMap = new Map()
  const rootNodes = []

  // 创建所有节点
  menus.forEach(menu => {
    menuMap.set(menu.menuId, {
      ...menu,
      expand: menu.visible === '1',
      children: []
    })
  })

  // 构建父子关系
  menus.forEach(menu => {
    const currentNode = menuMap.get(menu.menuId)
    if (menu.parentId === 0) {
      rootNodes.push(currentNode)
    } else {
      const parentNode = menuMap.get(menu.parentId)
      if (parentNode) {
        parentNode.children.push(currentNode)
      }
    }
  })

  // 排序
  rootNodes.sort((a, b) => a.orderNum - b.orderNum)
  rootNodes.forEach(node => {
    if (node.children) {
      node.children.sort((a, b) => a.orderNum - b.orderNum)
    }
  })

  // 创建虚拟根节点
  return {
    menuId: 0,
    menuName: 'XX科技有限公司',
    expand: true,
    children: rootNodes
  }
}

// 创建默认组织结构
const createDefaultStructure = async () => {
  const defaultStructure = [
    {
      menuName: '产品研发部',
      parentId: 0,
      orderNum: 1,
      children: [
        { menuName: '研发-前端', parentId: null, orderNum: 1 },
        { menuName: '研发-后端', parentId: null, orderNum: 2 },
        { menuName: 'UI设计', parentId: null, orderNum: 3 },
        { menuName: '产品经理', parentId: null, orderNum: 4 }
      ]
    },
    {
      menuName: '销售部',
      parentId: 0,
      orderNum: 2,
      children: [
        { menuName: '销售一部', parentId: null, orderNum: 1 },
        { menuName: '销售二部', parentId: null, orderNum: 2 }
      ]
    },
    { menuName: '财务部', parentId: 0, orderNum: 3 },
    { menuName: 'HR人事', parentId: 0, orderNum: 4 }
  ]

  // 递归创建默认结构
  const createNodes = async (nodes, parentId = 0) => {
    for (const node of nodes) {
      const menuData = {
        menuName: node.menuName,
        parentId: parentId,
        orderNum: node.orderNum,
        visible: '1',
        menuType: 'M',
        path: `/org/${Date.now()}`,
        perms: 'org:view',
        remark: 'org_structure'
      }

      const res = await addMenu(menuData)
      if (res.code === 200 && node.children) {
        await createNodes(node.children, res.data)
      }
    }
  }

  await createNodes(defaultStructure)
  await loadOrgData() // 重新加载数据
}

// 节点点击事件
const handleNodeClick = (event, data) => {
  currentNode.value = data
  console.log('点击节点:', data)
}

// 右键菜单事件
const handleContextMenu = (event, data) => {
  event.preventDefault()
  currentNode.value = data

  contextMenu.x = event.clientX
  contextMenu.y = event.clientY
  contextMenu.visible = true

  // 点击其他地方关闭菜单
  const closeMenu = () => {
    contextMenu.visible = false
    document.removeEventListener('click', closeMenu)
  }
  nextTick(() => {
    document.addEventListener('click', closeMenu)
  })
}

// 添加根组织
const handleAddRoot = () => {
  currentNode.value = null
  resetForm()
  dialog.title = '添加根组织'
  form.parentId = 0
  dialog.visible = true
}

// 添加同级组织
const handleAddSameLevel = () => {
  if (!currentNode.value) return
  resetForm()
  dialog.title = '添加同级组织'
  form.parentId = currentNode.value.parentId || 0
  dialog.visible = true
}

// 添加下级组织
const handleAddSubLevel = () => {
  if (!currentNode.value) return
  resetForm()
  dialog.title = '添加下级组织'
  form.parentId = currentNode.value.menuId
  dialog.visible = true
}

// 修改信息
const handleEdit = () => {
  if (!currentNode.value) return
  resetForm()
  dialog.title = '修改组织信息'
  Object.assign(form, currentNode.value)
  dialog.visible = true
}

// 删除信息
const handleDelete = async () => {
  if (!currentNode.value) return

  try {
    await ElMessageBox.confirm(
        `确定删除组织"${currentNode.value.menuName}"吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const res = await delMenu(currentNode.value.menuId)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      await loadOrgData()
    }
  } catch (error) {
    console.log('取消删除')
  }
}

// 表单提交
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 设置路径和权限（避免冲突）
        if (!form.path) {
          form.path = `/org/node/${Date.now()}`
        }
        if (!form.perms) {
          form.perms = `org:node:view:${Date.now()}`
        }

        let res
        if (form.menuId) {
          res = await updateMenu(form)
        } else {
          res = await addMenu(form)
        }

        if (res.code === 200) {
          ElMessage.success(form.menuId ? '修改成功' : '添加成功')
          dialog.visible = false
          await loadOrgData()
        }
      } catch (error) {
        console.error('操作失败:', error)
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  form.menuId = undefined
  form.menuName = ''
  form.orderNum = 0
  form.visible = '1'
  form.path = ''
  form.perms = ''
}

// 展开全部
const expandAll = () => {
  // 这里需要递归设置所有节点的 expand 为 true
  // 由于 vue3-tree-org 的限制，可能需要重新构建数据
  ElMessage.info('展开全部功能需要额外实现')
}

// 折叠全部
const collapseAll = () => {
  ElMessage.info('折叠全部功能需要额外实现')
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.org-chart-container {
  min-height: 600px;
  padding: 20px;
  background: #fafafa;
  border-radius: 4px;
}

.context-menu {
  position: fixed;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 2000;
}

.menu-item {
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
}

.menu-item:hover {
  background: #f5f7fa;
}

.menu-item.danger {
  color: #f56c6c;
}

.menu-item.danger:hover {
  background: #fef0f0;
}

:deep(.custom-org-node) {
  padding: 8px 12px;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  text-align: center;
  min-width: 120px;
}

:deep(.node-content) {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

:deep(.node-title) {
  font-weight: 500;
  color: #303133;
}
</style>